<template>
  <div v-if="visible" class="modal-overlay" @click.self="handleClose">
    <div class="modal card">
      <div class="modal-header">
        <h3>{{ editMode ? '编辑批次' : '新建批次' }}</h3>
        <button class="btn" @click="handleClose">✕</button>
      </div>
      <div class="modal-body">
        <div class="form-row">
          <label class="form-label">品牌</label>
          <div v-if="!isCreatingBrand" class="select-group">
            <select v-model="selectedBrand" class="select">
              <option value="">请选择品牌</option>
              <option v-for="brand in localBrands" :key="brand.id" :value="brand.name">
                {{ brand.name }}
              </option>
            </select>
            <button class="btn btn-small" @click="startCreateBrand">新建</button>
          </div>
          <div v-else class="create-brand-form">
            <div class="brand-input-row">
              <input v-model="newBrandName" class="input" type="text" placeholder="输入品牌名称" />
              <button class="btn btn-small btn-success" @click="confirmCreateBrand">确认</button>
              <button class="btn btn-small btn-secondary" @click="cancelCreateBrand">取消</button>
            </div>
            <div class="file-input-row">
              <label class="file-label">选择LOGO图片：</label>
              <input
                class="file-input"
                type="file"
                accept="image/*"
                @change="onBrandLogoSelected"
              />
            </div>
          </div>
        </div>

        <!-- 品牌LOGO预览行 -->
        <div class="form-row">
          <label class="form-label">品牌LOGO</label>
          <div class="logo-preview-row">
            <div class="logo-container">
              <img
                class="logo-preview"
                :src="
                  isCreatingBrand
                    ? brandLogoPreview || generateLogoPlaceholder(newBrandName || 'LOGO')
                    : selectedBrandLogo || generateLogoPlaceholder(selectedBrand || 'LOGO')
                "
                alt="品牌LOGO"
              />
            </div>
          </div>
        </div>

        <div class="form-row">
          <label class="form-label">季次</label>
          <div v-if="!isCreatingSeason" class="select-group">
            <select v-model="selectedSeason" class="select">
              <option value="">请选择季次</option>
              <option v-for="season in localSeasons" :key="season.id" :value="season.name">
                {{ season.name }}
              </option>
            </select>
            <button class="btn btn-small" @click="startCreateSeason">新建</button>
          </div>
          <div v-else class="input-group">
            <input v-model="newSeasonName" class="input" type="text" placeholder="输入季次名称" />
            <button class="btn btn-small btn-success" @click="confirmCreateSeason">确认</button>
            <button class="btn btn-small btn-secondary" @click="cancelCreateSeason">取消</button>
          </div>
        </div>

        <div class="form-row">
          <label class="form-label">批次名称</label>
          <div class="input-group">
            <input
              v-model="batchName"
              class="input"
              type="text"
              placeholder="例如：BrandA-2025SS"
            />
            <button class="btn btn-small icon-btn" @click="refreshBatchName" title="根据选择刷新">
              ⟳
            </button>
          </div>
        </div>

        <p v-if="errorMessage" class="error-text">{{ errorMessage }}</p>
      </div>
      <div class="modal-footer">
        <button class="btn" @click="handleClose" :disabled="submitting">取消</button>
        <button class="btn btn-primary" @click="handleSubmit" :disabled="!canSubmit || submitting">
          {{ submitting ? (editMode ? '保存中...' : '创建中...') : editMode ? '保存' : '创建' }}
        </button>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, watch, computed } from 'vue'
import { createBatch, updateBatch } from '../api/batchApi'
import { generateLogoPlaceholder, getDefaultLogo } from '../utils/logoPlaceholder'
import { ElMessage } from 'element-plus'

export default {
  name: 'CreateBatchDialog',
  props: {
    visible: { type: Boolean, default: false },
    brands: { type: Array, default: () => [] },
    seasons: { type: Array, default: () => [] },
    editMode: { type: Boolean, default: false },
    batchData: { type: Object, default: null },
  },
  emits: ['close', 'created', 'updated', 'conflict'],
  setup(props, { emit }) {
    const selectedBrand = ref('')
    const selectedSeason = ref('')
    const batchName = ref('')
    const submitting = ref(false)
    const errorMessage = ref('')
    const isCreatingBrand = ref(false)
    const isCreatingSeason = ref(false)
    const newBrandName = ref('')
    const newSeasonName = ref('')

    const localBrands = ref([])
    const localSeasons = ref([])
    const brandLogoFile = ref(null)
    const brandLogoPreview = ref('')

    // 默认LOGO占位图
    const defaultLogo = getDefaultLogo()

    const selectedBrandLogo = computed(() => {
      const found = localBrands.value.find(b => b.name === selectedBrand.value)
      return found && found.logo ? found.logo : ''
    })

    // 同步父级传入的选项到本地列表
    const syncLocalLists = () => {
      localBrands.value = (props.brands || []).map(b => ({ id: b.id, name: b.name, logo: b.logo }))
      localSeasons.value = (props.seasons || []).map(s => ({ id: s.id, name: s.name }))
    }

    // 初始化编辑数据
    const initEditData = () => {
      if (props.editMode && props.batchData) {
        selectedBrand.value = props.batchData.brand || ''
        selectedSeason.value = props.batchData.season || ''
        batchName.value = props.batchData.name || ''
      } else {
        selectedBrand.value = ''
        selectedSeason.value = ''
        batchName.value = ''
      }
      errorMessage.value = ''
      isCreatingBrand.value = false
      isCreatingSeason.value = false
      newBrandName.value = ''
      newSeasonName.value = ''
      brandLogoFile.value = null
      brandLogoPreview.value = ''
    }

    watch(() => props.brands, syncLocalLists, { immediate: true, deep: true })
    watch(() => props.seasons, syncLocalLists, { immediate: true, deep: true })
    watch(
      () => props.visible,
      v => {
        if (v) {
          syncLocalLists()
          initEditData()
        }
      }
    )

    const canSubmit = computed(() => {
      return Boolean(selectedBrand.value && selectedSeason.value && batchName.value)
    })

    watch([() => props.visible, selectedBrand, selectedSeason], () => {
      if (!props.visible) return
      if (!batchName.value && !props.editMode) {
        if (selectedBrand.value && selectedSeason.value) {
          batchName.value = `${selectedBrand.value}-${selectedSeason.value}`
        }
      }
    })

    const refreshBatchName = () => {
      if (selectedBrand.value && selectedSeason.value) {
        batchName.value = `${selectedBrand.value}-${selectedSeason.value}`
      }
    }

    const onBrandLogoSelected = e => {
      const file = e && e.target && e.target.files && e.target.files[0]
      if (!file) return
      brandLogoFile.value = file
      const reader = new FileReader()
      reader.onload = () => {
        brandLogoPreview.value = reader.result
      }
      reader.readAsDataURL(file)
    }

    // 品牌新建相关方法
    const startCreateBrand = () => {
      isCreatingBrand.value = true
      newBrandName.value = ''
      brandLogoFile.value = null
      brandLogoPreview.value = ''
    }

    const confirmCreateBrand = () => {
      const name = newBrandName.value.trim()
      if (!name) return
      // 将新品牌加入到下拉列表
      const exists = localBrands.value.some(b => b.name === name)
      if (!exists) {
        localBrands.value = [
          ...localBrands.value,
          { id: `custom-${name}`, name, logo: brandLogoPreview.value },
        ]
      }
      selectedBrand.value = name
      isCreatingBrand.value = false
      newBrandName.value = ''
      // 预览保留，供显示
    }

    const cancelCreateBrand = () => {
      isCreatingBrand.value = false
      newBrandName.value = ''
      brandLogoFile.value = null
      brandLogoPreview.value = ''
      errorMessage.value = ''
    }

    // 季次新建相关方法
    const startCreateSeason = () => {
      isCreatingSeason.value = true
      newSeasonName.value = ''
    }

    const confirmCreateSeason = () => {
      const name = newSeasonName.value.trim()
      if (!name) return
      // 将新季次加入到下拉列表
      const exists = localSeasons.value.some(s => s.name === name)
      if (!exists) {
        localSeasons.value = [...localSeasons.value, { id: `custom-${name}`, name }]
      }
      selectedSeason.value = name
      isCreatingSeason.value = false
      newSeasonName.value = ''
    }

    const cancelCreateSeason = () => {
      isCreatingSeason.value = false
      newSeasonName.value = ''
    }

    const handleClose = () => {
      if (submitting.value) return
      emit('close')
      // 重置状态以便下次打开
      initEditData()
    }

    const handleSubmit = async () => {
      console.log('🚀 ~ handleSubmit ~ handleSubmit:')
      if (!canSubmit.value) return
      submitting.value = true
      errorMessage.value = ''
      try {
        const payload = {
          name: batchName.value,
          brand: selectedBrand.value,
          season: selectedSeason.value,
        }
        if (brandLogoPreview.value) {
          payload.brandLogoBase64 = brandLogoPreview.value
        }

        if (props.editMode) {
          // 编辑模式
          const res = await updateBatch(props.batchData.id, payload)
          window.$toast?.showSuccess('更新成功')
          emit('updated', res)
        } else {
          // 新建模式
          const res = await createBatch(payload)
          window.$toast?.showSuccess('创建成功')
          emit('created', res)
        }
        handleClose()
      } catch (err) {
        console.error(props.editMode ? '更新批次失败:' : '创建批次失败:', err)
        // 处理错误响应
        if (err?.response?.data) {
          const errorData = err.response.data
          // 检查响应体中的code字段是否为错误码
          if (errorData.code && errorData.code !== 200) {
            errorMessage.value =
              errorData.message ||
              (props.editMode ? '更新失败，请稍后重试' : '创建失败，请稍后重试')

            // 如果有冲突批次信息，传递给父组件
            if (errorData.data?.conflict_batch_id) {
              emit('conflict', errorData.data)
            }
          } else {
            // 如果code是200，说明是成功响应，不应该进入catch块
            errorMessage.value = '未知错误，请稍后重试'
          }
        } else {
          errorMessage.value =
            err?.message || (props.editMode ? '更新失败，请稍后重试' : '创建失败，请稍后重试')
        }
      } finally {
        submitting.value = false
      }
    }

    return {
      selectedBrand,
      selectedSeason,
      batchName,
      submitting,
      errorMessage,
      isCreatingBrand,
      isCreatingSeason,
      newBrandName,
      newSeasonName,
      localBrands,
      localSeasons,
      brandLogoFile,
      brandLogoPreview,
      selectedBrandLogo,
      defaultLogo,
      generateLogoPlaceholder,
      onBrandLogoSelected,
      canSubmit,
      refreshBatchName,
      startCreateBrand,
      confirmCreateBrand,
      cancelCreateBrand,
      startCreateSeason,
      confirmCreateSeason,
      cancelCreateSeason,
      handleClose,
      handleSubmit,
    }
  },
}
</script>

<style scoped>
.modal-overlay {
  position: fixed;
  inset: 0;
  background: rgba(0, 0, 0, 0.35);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal {
  width: 520px;
  max-width: 92vw;
}

.modal-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;
}

.modal-body {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  margin-top: 12px;
}

.form-row {
  display: flex;
  align-items: center;
  gap: 12px;
}

.select-group {
  display: flex;
  align-items: center;
  gap: 8px;
  flex: 1;
}

.input-group {
  display: flex;
  align-items: center;
  gap: 8px;
  flex: 1;
}

.form-label {
  min-width: 72px;
  color: var(--text-secondary);
}

.btn-small {
  padding: 6px 12px;
  font-size: 12px;
  white-space: nowrap;
}

.icon-btn {
  width: 32px;
  height: 32px;
  padding: 0;
  display: inline-flex;
  align-items: center;
  justify-content: center;
}

.btn-success {
  background: var(--success-color);
  border-color: var(--success-color);
  color: white;
}

.btn-success:hover {
  background: #389e0d;
  border-color: #389e0d;
  color: white;
}

.btn-secondary {
  background: var(--text-secondary);
  border-color: var(--text-secondary);
  color: white;
}

.btn-secondary:hover {
  background: #595959;
  border-color: #595959;
  color: white;
}

.input {
  flex: 1;
  padding: 8px 10px;
  border: 1px solid var(--border-color);
  border-radius: var(--border-radius);
  background: var(--card-background);
}

.error-text {
  color: var(--error-color);
}

.logo-container {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  flex-shrink: 0;
}

.logo-preview {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 4px;
  border: 1px solid var(--border-color);
}

.file-input {
  font-size: 12px;
  max-width: 200px;
}

.create-brand-form {
  display: flex;
  flex-direction: column;
  gap: 8px;
  flex: 1;
}

.brand-input-row {
  display: flex;
  align-items: center;
  gap: 8px;
}

.file-input-row {
  display: flex;
  align-items: center;
  gap: 8px;
}

.file-label {
  font-size: 13px;
  color: var(--text-secondary);
  white-space: nowrap;
}

.logo-preview-row {
  display: flex;
  align-items: center;
  gap: 8px;
}

.logo-placeholder {
  color: var(--text-secondary);
  font-size: 13px;
}
</style>
